#include "login.h"
#include "../doctor/doctor_client.h"
#include "../patient/patient_client.h"
#include "../common/database.h"

#include <QFormLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

Login::Login(QWidget *parent) : QWidget(parent)
{
    setWindowTitle("Login");
    resize(400, 200);  // 调整窗口大小

    // 初始化数据库连接
    if (!Database::connect()) {
        QMessageBox::critical(this, "Database Error", "Failed to connect to the database.");
        close();
        return;
    }

    // 创建布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 表单布局用于用户名和密码输入
    QFormLayout *formLayout = new QFormLayout();
    usernameInput = new QLineEdit(this);
    passwordInput = new QLineEdit(this);
    passwordInput->setEchoMode(QLineEdit::Password);  // 隐藏密码输入

    formLayout->addRow("Username:", usernameInput);
    formLayout->addRow("Password:", passwordInput);

    mainLayout->addLayout(formLayout);

    // 医生和患者的登录按钮
    QPushButton *doctorButton = new QPushButton("Doctor Login", this);
    QPushButton *patientButton = new QPushButton("Patient Login", this);
    mainLayout->addWidget(doctorButton);
    mainLayout->addWidget(patientButton);

    // 连接按钮信号槽
    connect(doctorButton, &QPushButton::clicked, this, &Login::onDoctorLogin);
    connect(patientButton, &QPushButton::clicked, this, &Login::onPatientLogin);
}

void Login::onDoctorLogin()
{
    QString username = usernameInput->text();
    QString password = passwordInput->text();

    // 验证凭据
    if (validateCredentials(username, password, "doctor")) {
        // 凭据验证通过后，查询医生的 ID
        QSqlQuery query;
        query.prepare("SELECT doctor_id FROM doctors WHERE name = :username");
        query.bindValue(":username", username);

        int loggedInDoctorId = -1;
        if (query.exec() && query.next()) {
            loggedInDoctorId = query.value(0).toInt(); // 获取 doctor_id
        } else {
            // 查询失败，显示错误信息
            QMessageBox::warning(this, "Error", "Failed to retrieve doctor ID: " + query.lastError().text());
            return;
        }

        // 创建并显示 DoctorClient 界面，传递 doctorId
        auto *doctorClient = new DoctorClient(loggedInDoctorId);
        doctorClient->show();

        close(); // 关闭登录窗口
    } else {
        QMessageBox::warning(this, "Login Failed", "Invalid name or password.");
    }
}


void Login::onPatientLogin()
{
    QString username = usernameInput->text();
    QString password = passwordInput->text();

    if (validateCredentials(username, password, "patient")) {
        auto *patientClient = new PatientClient(username);
        patientClient->show();
        close();  // 关闭登录窗口
    } else {
        QMessageBox::warning(this, "Login Failed", "Invalid name or password.");
    }
}

bool Login::validateCredentials(const QString &username, const QString &password, const QString &userType)
{
    QSqlQuery query;
    QString tableName;

    // 根据用户类型选择表名
    if (userType == "doctor") {
        tableName = "doctors";  // 医生表
    } else if (userType == "patient") {
        tableName = "patients";  // 患者表
    }

    // 准备查询
    query.prepare(QString("SELECT COUNT(*) FROM %1 WHERE name = ? AND password = ?").arg(tableName));
    query.addBindValue(username);
    query.addBindValue(password);

    if (query.exec() && query.next()) {
        return query.value(0).toInt() > 0;  // 返回查询结果是否大于 0
    } else {
        qDebug() << "Database query error:" << query.lastError().text();
        return false;
    }
}

